有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如果没有调用其他方法,如何调用方法?

我正在尝试设置一个类,该类包含一个特定的值,然后可以用作它的默认值。例如:

public class Account {
  private GUID;
  private balance;

  public Account(int balance) {
    this.balance = balance;
    this.GUID = new GUID();
  }

  public getBalance() {
    return this.balance;
  }

然后在使用过程中,我会以某种方式完成以下工作:

Account test = new Account(40);
System.out.println("Account balance: " + test);

这将返回:Account balance: 40

不必写:

Account test = new Account(40);
System.out.println("Account balance: " + test.getBalance());

有没有一种在Java中实现这一点的方法


共 (4) 个答案

  1. # 1 楼答案

    首先,您编写它的方式使它看起来像2.5个类(或一个包含2个构造函数的类),而不是一个包含您想要的某些方法的类

    要让课堂按原样进行,请将课堂改为如下:

    public class Account 
    {
      private GUID; //Not sure if this needs a type or if GUID is the type!
      private double balance; //Added the double type, which holds a decimal
    
      public Account(int balance) //This is your constructor: no return type
      { 
        this.balance = balance;
        this.GUID = new GUID();
      }
    
      public double getBalance()  //Added return type for this method 
      {
        //Now it will return the number.
        return this.balance;
      }
    
      //Now to override the toString method for the class:
      public String toString()  //Notice this one returns String
      {
        return "Account balance: $" + this.balance.toString();
      }
    }
    

    因此,根据需要,您现在可以执行Account test = new Account(40);,这将基于您的类创建一个新对象,余额为40。您可以只提取数字并将其存储在一个变量中,以便进行操作或通过如下操作添加总数:double theBalance = test.getBalance();如果您只需在对象上调用toString(),test.toString();它将返回Account balance: $40.0的奇特输出

    请注意,原始双精度可以有许多小数点,因此您可能希望在toString函数中对这些值进行四舍五入,以使其更精确。由于已将平衡变量设置为专用变量,因此还需要创建一个“setter”函数,以便在创建对象后更改平衡,因为当前只能在创建对象的过程中对其进行设置。也许你可以在每次更新时对值进行取整,这样就不会对客户的余额产生任何困惑

    希望这能有所帮助,如果你还有问题,请留言!Java也是我的第一语言,在我完全理解对象之前,它有点疯狂,但一旦你把你的头绕在它们周围。。。令人惊讶的是,一切都变得如此简单。你现在正在学习它们,这很好

  2. # 2 楼答案

    为了实现您的要求,您需要重写类中的toString()方法,该方法从Object类继承(Java中的所有类都从Object类继承)

    您可以向方法的代码中添加如下内容:

    public String toString() {
        return this.balance;
    }
    

    重写该方法后,当调用System.out.println(test)时,您将在输出上看到从测试对象分配给balance字段的值

  3. # 3 楼答案

    像这样做

    public class Account {
       private GUID guid;
       private int balannce;
    
     public Account(int balance) {
        this.balance = balance;
        this.guid = new GUID();
      }
    
      public getBalance() {
        return this.balance; 
      }      
    
      @Override
      public String toString() {
        return String.format("%03d", balance);
      }
    }
    
  4. # 4 楼答案

    恐怕你不能那样做

    您可以为此定义一个toString()方法。 因为如果你直接输入对象(没有任何方法),显然会打印出该对象的地址,而不是其变量的内部值

    所以是的,你不能这么做

    希望这能帮到你